﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Input;
using Ionic.Zip;
using ResxHelper.Object;

namespace ResxHelper.Logic.Actions
{
    public class SaveZipAction : ICommand
    {
       
        private readonly SaveZipRequest _input;

        public SaveZipAction(SaveZipRequest input)
        {
            _input = input;
        }

        public bool CanExecute(object parameter)
        {
            return (_input.FilePaths.All(File.Exists) || _input.FilePaths.All(Directory.Exists)) &&
                   _input.SaveDirectory != string.Empty &&
                   _input.SaveDirectory != "";
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            var paths = _input.FilePaths.ToArray();

            string fileName;
            if (Path.GetExtension(_input.SaveDirectory) != ".zip")
            {
                fileName = string.Format("{0}\\{1}.zip", _input.SaveDirectory,
                    Path.GetFileNameWithoutExtension(paths[0]));
            }
            else
            {
                fileName = _input.SaveDirectory;
            }    

            using (var zip = new ZipFile())
            {
                foreach (var path in paths)
                {
                    zip.AddFile(path, "");
                }
                zip.Save(fileName);
            }

            if (!_input.DeleteFiles) return;

            _input.FilePaths
                .ToList()
                .ForEach(File.Delete);
        }
    }
}
